<template>
  <div
    class="head-image"
    @click="showUserInfo($event)"
    :style="{ cursor: isShowUserInfo ? 'pointer' : undefined }"
  >
    <img
      class="avatar-image"
      v-show="url"
      :src="url"
      :style="avatarImageStyle"
      loading="lazy"
    />
    <div class="avatar-text" v-show="!url" :style="avatarTextStyle">
      {{ name?.substring(0, 2).toUpperCase() }}
    </div>
    <div v-show="online" class="online" title="用户当前在线"></div>
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";

const colors = [
  "#5daa31",
  "#c7515a",
  "#e03697",
  "#85029b",
  "#c9b455",
  "#326eb6",
];
const props = defineProps({
  id: Number,
  size: Number,
  width: Number,
  height: Number,
  url: String,
  name: String,
  online: Boolean,
  isShowUserInfo: Boolean,
  radius: {
    type: String,
    default: "50%",
  },
});
const avatarImageStyle = computed(() => {
  let w = props.width || props.size;
  let h = props.height || props.size;
  return `
        width:${w}px; 
        height:${h}px;
        border-radius: ${props.radius};
    `;
});
const avatarTextStyle = computed(() => {
  let w: number = props.width || props.size || 0;
  let h = props.height || props.size;
  return ` 
        width: ${w}px;
        height:${h}px;
        background-color: ${props.name ? textColor.value : "#fff"};
        font-size:${w * 0.35}px;
        border-radius: ${props.radius};
  `;
});
const textColor = computed(() => {
  let hash = 0;
  if (props.name) {
    for (var i = 0; i < props.name.length; i++) {
      hash += props.name.charCodeAt(i);
    }
  }

  return colors[hash % colors.length];
});

function showUserInfo(e: MouseEvent) {
  if (!props.isShowUserInfo) return;
  if (props.id && props.id > 0) {
    // this.$http({
    //   url: `/user/find/${this.id}`,
    //   method: "get",
    // }).then((user) => {
    //   let pos = {
    //     x: e.x + 30,
    //     y: e.y,
    //   };
    //   this.$eventBus.$emit("openUserInfo", user, pos);
    // });
  }
}
</script>

<style lang="scss" scoped>
.head-image {
  position: relative;

  .avatar-image {
    position: relative;
    overflow: hidden;
    display: block;
  }

  .avatar-text {
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .online {
    position: absolute;
    right: -5px;
    bottom: 0;
    width: 12px;
    height: 12px;
    background: limegreen;
    border-radius: 50%;
    border: 2px solid white;
  }
}
</style>
